<template>
  <k-form-modal
    ref="formRef"
    drawer
    center
    width="650px"
    :title="state.mode === 1 ? '编辑活动' : '创建活动'"
    label-width="82px"
    hide-required-asterisk
    v-bind="formModalState"
    v-on="formModalEvent"
  >
    <el-form-item label="活动标题" prop="title" :rules="[{ required: true, message: '请输入活动标题' }]">
      <el-input v-model="state.model.title" placeholder="请输入活动标题" />
    </el-form-item>
    <el-form-item label="活动时间" prop="_timeArr" :rules="[{ required: true, message: '请选择时间' }]">
      <el-date-picker
        v-model="state.model._timeArr"
        type="daterange"
        format="YYYY-MM-DD"
        value-format="YYYYMMDD"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      />
    </el-form-item>
    <el-form-item prop="main_banner_url" :rules="[{ required: true, message: '请选择图片' }]">
      <template #label>
        <div class="link-label">
          <div>banner图</div>
          <div>（主图）</div>
        </div>
      </template>
      <KImageUploader ref="uploadMainRef" :file-list="fileListMain" :limit="1" :on-before-upload="v=>onBeforeUpload(v,1)" />
      <div class="tip">图片建议尺寸1053*330</div>
    </el-form-item>
    <el-form-item prop="page_banner_url" :rules="[{ required: true, message: '请选择图片' }]">
      <template #label>
        <div class="link-label">
          <div>banner图</div>
          <div>（页面图）</div>
        </div>
      </template>
      <KImageUploader ref="uploadPageRef" :file-list="fileListPage" :limit="1" :on-before-upload="v=>onBeforeUpload(v,2)" />
      <div class="tip">图片建议尺寸1125*240</div>
    </el-form-item>
    <el-form-item
      prop="activity_id"
      :rules="[
        { pattern: /^[0-9]*$/, message: '信息ID必须为整数'}]"
    >
      <template #label>
        <div class="link-label">
          <div>关联活动</div>
          <div>信息ID</div>
        </div>
      </template>
      <el-input v-model="state.model.activity_id" placeholder="请输入（选填）" />
    </el-form-item>
    <el-form-item
      prop="priority"
      :rules="[{ required: true, message: '请设置优先级' },
               { pattern: /^[0-9]*$/, message: '优先级必须为整数'}]"
    >
      <template #label>
        <div class="priority-label">
          优先级
          <el-tooltip content="数值越大，展示排序越靠前" placement="top">
            <img width="16" height="16" src="@/assets/images/icons/question-help.png">
          </el-tooltip>
        </div>
      </template>
      <el-input v-model="state.model.priority" placeholder="请输入" />
    </el-form-item>
    <el-form-item label="上架状态" prop="status">
      <el-switch v-model="state.model.status" :active-value="1" :inactive-value="2" active-text="上架" inactive-text="下架" @change="onChange" />
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang="ts">
import { defineComponent, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { useFormModal, baseConfirm } from '@crud/index';
import { KImageUploader } from '@/components/k-image-uploader2';
import { activityAdd, activityEdit } from '@/api/crm-kgj/activity';
defineComponent({ name: 'CreateBannerDrawer' });
const emits = defineEmits(['submit']);

const formRef = ref();
const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {
    title: '',
    activity_id: '',
    main_banner_url: undefined,
    page_banner_url: undefined,
    priority: '',
    status: 1,
    platform: 2 // 1-web  2-app
  },
  onShow: (mode = 0, data: any) => {
    fileListMain.value = [];
    fileListPage.value = [];

    if (data) {
      state.model = {
        id: data.id,
        title: data.title,
        _timeArr: [dayjs.unix(data.begin_time).format('YYYYMMDD'), dayjs.unix(data.end_time).format('YYYYMMDD')],
        main_banner_url: data.main_banner_url,
        page_banner_url: data.page_banner_url,
        activity_id: data.activity_id,
        priority: data.priority,
        status: data.activity_status
      };
      fileListMain.value = [{
        uid: -1,
        name: data.main_banner_url,
        url: data.main_banner_url
      }];
      fileListPage.value = [{
        uid: -1,
        name: data.page_banner_url,
        url: data.page_banner_url
      }];
    }
  },
  onSubmit: async (model: any, mode = 0) => {
    const params = {
      ...model,
      main_banner_url: model?.main_banner_url?.url ? model.main_banner_url.url : model.main_banner_url,
      page_banner_url: model?.page_banner_url?.url ? model.page_banner_url.url : model.page_banner_url,
      begin_time: dayjs(model._timeArr[0]).unix(),
      end_time: dayjs(model._timeArr[1]).unix(),
      _timeArr: undefined
    };
    const api = mode === 1 ? activityEdit : activityAdd;
    const res = await api(params);
    if (!res.err) {
      ElMessage.success(mode===1 ? '编辑成功': '创建成功');
      emits('submit');
    }
    return res;
  }
});

// 上架状态
const onChange = async(val: number) => {
  if (val === 2) {
    state.model.status = 1;
    const res = await baseConfirm({ type: 'none', title: '下架活动', message: '该活动状态将变更为下架状态，无法展示，如需继续请点击确认。' });
    if (res) state.model.status = 2;
  }
};

// 图片上传
const uploadMainRef = ref();
const uploadPageRef = ref();
/** 默认图片 */
const fileListMain = ref<Record<string, any>[]>([]);
const fileListPage = ref<Record<string, any>[]>([]);
const onBeforeUpload = (file, type = 1) => {
  const typeMap = {
    1: { // 主图
      width: 1053,
      height: 330
    },
    2: { // 首页图
      width: 1125,
      height: 240
    }
  };
  const { width: bannerWidth, height: bannerHeight } = typeMap[type];
  const isSize = new Promise((resolve, reject) => {
    const _URL = window.URL || window.webkitURL;
    let img = new Image();
    img.onload = function() {
      const width = img.width;// 获取图片的宽
      const height = img.height;// 获取图片的高
      (width%bannerWidth) === 0 && (height%bannerHeight)=== 0 ? resolve() : reject();
    };
    img.src = _URL.createObjectURL(file);
  }).then(() => {
    return file;
  }, () => {
    ElMessage.error(`图片建议尺寸${bannerWidth}*${bannerHeight}`);
    return Promise.reject();
  });
  return isSize;
};
watch(() => uploadMainRef?.value?.getImgUrl(),
  (val) => {
    state.model.main_banner_url = val;
  },
  {
    immediate: false
  });
watch(() => uploadPageRef?.value?.getImgUrl(),
  (val) => {
    state.model.page_banner_url = val;
  },
  {
    immediate: false
  });

defineExpose({
  show: methods.show
});
</script>

<style lang="scss" scoped>
.title {
  margin-bottom: 18px;
  font-size: 18px;
  font-weight: 500;
  line-height: 26px;
  color: #303133;
}

.link-label {
  line-height: 18px;
  text-align: right;
}

.priority-label {
  display: flex;
  align-items: center;
}

.tip {
  margin-left: 8px;
  color: #A8ABB2;
}
</style>
